package com.yunti.springboot.config.component;

import com.alibaba.fastjson.JSONObject;
import com.yunti.springboot.bo.UserBO;
import com.yunti.springboot.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 线上获取当前登录用户信息
 *
 * @author yxp
 */
@Slf4j
@Component
public class ProdAbstractCurrentRequestComponent extends AbstractCurrentRequestComponent {
    /**
     * 当前线程的用户变量
     */
    private ThreadLocal<UserBO> threadLocalUser = new ThreadLocal<>();


    /**
     * 获取当前登陆用户信息
     *
     * @return 当前登录用户信息
     */
    @Override
    public UserBO getCurrentStaffId() {
        if(Objects.nonNull(threadLocalUser.get())){
            return threadLocalUser.get();
        }
        HttpServletRequest request = Optional.ofNullable((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .map(ServletRequestAttributes::getRequest).orElse(null);
        if(request == null){
            return null;
        }
        String token = request.getHeader(REQUEST_HEADER_TOKEN);
        if (StringUtils.isBlank(token) || "null".equals(token) || "undefined".equals(token)) {
            return null;
        }
        Claims claims = null;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            return null;
        }
        if (claims == null){
            return null;
        }
        String userName = String.valueOf(claims.getSubject());
        String result = stringRedisTemplate.opsForValue().get(TOKEN_KEY + userName);
        stringRedisTemplate.opsForValue().set(TOKEN_KEY + userName, result,10, TimeUnit.HOURS);
        if (StringUtils.isNotBlank(result)) {
            UserBO oaUserBO = JSONObject.parseObject(result, UserBO.class);
            if (oaUserBO == null) {
                log.info("redis里tokenInfo为空");
                return null;
            }
            oaUserBO.setToken(token);
            return oaUserBO;
        }
        return null;
    }

    @Override
    public <R> R invokeWithUser(UserBO user, Function<UserBO,R> callback) {
        try {
            threadLocalUser.set(user);
            return callback.apply(user);
        } finally {
            threadLocalUser.remove();
        }
    }
}
